﻿using System;
using System.ComponentModel;
using System.Threading;
using IrcBot.Listener;

namespace IrcBot
{
    public class Program
    {
        private static SocketListener _listener;
        private static BackgroundWorker _worker;

        #region Main thread

        public static void Main()
        {
            try
            {
                StartListening();

                while (true)
                {
                    var input = Console.ReadLine();
                    if (!string.IsNullOrEmpty(input) && input.ToLower().Trim().Equals("quit"))
                    {
                        break;
                    }
                    Thread.Sleep(50);
                }
            }
            finally
            {
                StopListening();
            }
        }

        public static void StartListening()
        {
            if (_worker == null)
            {
                _worker = new BackgroundWorker();
                _worker.DoWork += StartSocketListener;
                _worker.WorkerReportsProgress = false;
                _worker.WorkerSupportsCancellation = true;
            }

            _worker.RunWorkerAsync();
        }

        public static void StopListening()
        {
            _listener.Dispose();
            _worker.CancelAsync();
            _worker.Dispose();
        }

        #endregion

        #region Listener thread

        private static void StartSocketListener(object sender, DoWorkEventArgs e)
        {
            _listener = new SocketListener();
        }

        #endregion
    }
}
